var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var app = express();
const jwt = require("jsonwebtoken");

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());

// 开放静态资源目录
app.use('/uploads', express.static('./uploads'));

// 配置跨域
const cors = require('cors');
app.use(cors());

// 首页
const index = require('./routes/index');
app.use("/index", index);

// 同步课程
const course = require('./routes/course');
app.use("/course", course);

// 搜索
const search = require('./routes/search');
app.use("/search", search);

// 课程详情
const detail = require('./routes/detail');
app.use("/detail", detail);

// ===========token验证=========
// app.use((req, res, next) => {
//   // 先验证token是否有效
//   let token = req.headers.token;
//   // 密匙
//   let sectet = '加一个密匙，不让你知道！！！';
//   try {
//     let decoded = jwt.verify(token, sectet);
//     next();
//   } catch {
//     next('该用户已掉线, 请重新登录');
//   }
// })
// =================================

// 课程报名
const personal = require('./routes/personal');
app.use("/personal", personal);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
  res.send({
    isok: false,
    status: 404,
    msg: '该请求不存在'
  })
});

// error handler
app.use(function(err, req, res, next) {
  res.send({
    isok: false,
    status: 500,
    msg: err
  })
});

module.exports = app;
